#include <QCoreApplication>
#include <windows.h>
#include <QDebug>
#include <handle_module.h>
#include <QSharedPointer>
#include <enum_type.h>
#include <common.h>
#include <setting.h>
QSharedPointer<Handle_module> handle1;

void MessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{

    QByteArray localMsg = msg.toLocal8Bit();
    switch (type) {
    case QtDebugMsg:
        fprintf(stderr, "%s\n", localMsg.constData());
        break;
    case QtInfoMsg:
        fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtWarningMsg:
        fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtCriticalMsg:
        fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        break;
    case QtFatalMsg:
        fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
        abort();
    }
    QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
    QString strMessage = QString("DateTime:%5   Message:%1   Function:%4   File:%2   Line:%3")
            .arg(msg).arg(context.file).arg(context.line).arg(context.function).arg(strDateTime);
    // 输出信息至文件中（读写、追加形式）
    common::LogdataLock.lockForWrite();
    common::Logdata.append(strMessage);
    common::LogdataLock.unlock();
    ///
    /// 没有启动日志会导致应用内存越来越大，因为Common::Logdata没有进行清除!!!
    ///
}

LONG ApplicationCrashHandler(EXCEPTION_POINTERS *pException){//程式异常捕获
    /*
      ***保存数据代码***
    */
    //这里弹出一个错误对话框并退出程序
    if(!handle1.isNull())
    {
        if(!handle1.data()->c_socket.isNull())
        {
            handle1.data()->c_socket.data()->send_message("exe","崩溃","程序崩溃");
        }
    }
    return EXCEPTION_EXECUTE_HANDLER;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
   qInstallMessageHandler(MessageOutput);
   SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);//注冊异常捕获函数
   QSharedPointer<Setting> mysetting= QSharedPointer<Setting>(new Setting());
   mysetting.data()->init("Caculate_Template");
   mysetting.data()->Start();
   common::ConfigureLock.lockForRead();
   QString Local_Port=common::Local_port;
   bool    Log_Open=common::Log_Open;
   common::ConfigureLock.unlock();
   if(!Log_Open)
   {
       qInstallMessageHandler(NULL);
   }
   QSharedPointer<Handle_module> handle=QSharedPointer<Handle_module>(new Handle_module(Local_Port));
   handle.data()->handle_init();

    return a.exec();
}
